﻿/***
 * 
 *    Title: "ZGUIFW"UI框架项目
 *           主题： Unity 帮助脚本      
 *    Description: 
 *           功能： 提供程序用户一些常用的方法 帮助开发者快速开发
 *    Date: 2018
 *    Version: 0.1版本
 */
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UnityHelper : MonoBehaviour 
{
    /// <summary>
    /// Finds the child node.
    /// </summary>
    /// <returns>The the child node.</returns>
    /// <param name="goParent">Go parent.</param>
    /// <param name="childName">Child name.</param>
    public static Transform FindTheChildNode(GameObject goParent, string childName)
    {
        Transform searchTrans = goParent.transform.Find(childName);
        if (searchTrans != null) return searchTrans;
        foreach (Transform trans in goParent.transform)
        {
            searchTrans = trans.Find(childName);
            if (searchTrans != null) return searchTrans;
        }
        return null;
    }
    /// <summary>
    /// Gets the child compont.
    /// </summary>
    /// <returns>The child compont.</returns>
    /// <param name="goParent">Go parent.</param>
    /// <param name="childName">Child name.</param>
    /// <typeparam name="T">The 1st type parameter.</typeparam>
    public static T GetChildCompont<T>(GameObject goParent, string childName) where T : Component
    {
        Transform searchTrans = FindTheChildNode(goParent, childName);
        if (searchTrans == null) return null;
        return searchTrans.GetComponent<T>();
    }
    /// <summary>
    /// Adds the child compont.
    /// </summary>
    /// <returns>The child compont.</returns>
    /// <param name="goParent">Go parent.</param>
    /// <param name="childName">Child name.</param>
    /// <typeparam name="T">The 1st type parameter.</typeparam>
    public static T AddChildCompont<T>(GameObject goParent, string childName) where T : Component
    {
        //先查找节点
        Transform searchTrans = FindTheChildNode(goParent, childName);
        if (searchTrans == null) return null;
        //考虑是否有相同的脚本
        T script = searchTrans.GetComponent<T>();
        if (script != null) Destroy(script);
        return searchTrans.gameObject.AddComponent<T>();
    }
    /// <summary>
    /// Sets the parent.
    /// </summary>
    /// <param name="parent">Parent.</param>
    /// <param name="childTrans">Child trans.</param>
    public static void SetParent(Transform parent, Transform childTrans)
    {
        childTrans.SetParent(parent, false);
        childTrans.localPosition = Vector3.zero;
        childTrans.localScale = Vector3.one;
        childTrans.localEulerAngles = Vector3.zero;
    }
}
